# -*- coding: UTF-8 -*-
from typing import List
from leetcode_helper import TestcaseHelper, SolutionBase


class Solution(SolutionBase):
    # 解题的方法，命名和Leetcode的保持一致即可
    def circularArrayLoop(self, nums: List[int]) -> bool:
        fast_pointer = 0
        slow_pointer = 0

        nums_count = len(nums)

        def next(cur:int) -> int:
            return (cur + nums[cur]) % nums_count  # 保证返回值在 [0,n) 中

        for i, num in enumerate(nums):
            if num == 0:
                continue
            slow_pointer = i
            fast_pointer = next(i)

            # 判断同号，因为fast要走两步，所以要比较slow和fast，以及slow和next（fast)
            while nums[slow_pointer] * nums[fast_pointer] > 0 and nums[slow_pointer] * nums[next(fast_pointer)] > 0:
                if slow_pointer == fast_pointer:
                    if slow_pointer == next(fast_pointer):
                        break
                    return True

                slow_pointer = next(slow_pointer)
                fast_pointer = next(next(fast_pointer))

            # 将从i开始、所有满足条件的nums设置为0，避免再次探测
            add = i
            while nums[add] * nums[next(add)] > 0:
                tmp = add
                add = next(tmp)
                nums[add] = 0

        return False

    def circularArrayLoop_simulate(self, nums: List[int]) -> bool:
        # 返回是否cur为循环的开始节点
        def check(cur: int) -> bool:
            k = 1
            start_gt_zero = nums[cur] > 0
            start = cur
            if nums[cur] == 0:
                return False

            while True:
                if k > nums_count:
                    return False

                next_index = (cur + nums[cur]) % nums_count
                if start_gt_zero and nums[next_index] < 0:
                    return False
                if not start_gt_zero and nums[next_index] > 0:
                    return False
                if start == next_index:
                    return k > 1

                cur = next_index
                k += 1

        nums_count = len(nums)
        for i in range(nums_count):
            if check(i):
                return True

        return False


if __name__ == '__main__':
    solution = Solution()

    # 按照leetcode的题目说明，将基本的test case填入
    # 每条case的最后一个元素是正确的结果，即期待的结果
    # 使用元组来保存输入的数据，期待的结果
    testcases = [
        ([2,-1,1,2,2], True),
        ([-1,2], False),
        ([-2,1,-1,-2,-2], False)
    ]

    for case_item in testcases:
        # 获取测试用的case和期待的执行结果
        input1 = case_item[0]
        expect = case_item[len(case_item) - 1]

        exec_result = solution.circularArrayLoop(input1)
        # 判断执行结果，输出提示信息
        check_result = solution.check_result(expect, exec_result)
        TestcaseHelper.print_case(check_result, case_item, exec_result)

        exec_result = solution.circularArrayLoop_simulate(input1)
        # 判断执行结果，输出提示信息
        check_result = solution.check_result(expect, exec_result)
        TestcaseHelper.print_case(check_result, case_item, exec_result)
